<?php
/**
 * Created by PhpStorm.
 * User: kb130
 * Date: 2018/5/24
 * Time: 13:50
 */

namespace App\Http\Middleware;

use App\Models\SlowQueryLog;
use DB;
use Closure;

/**
 * 慢查询收集中间件
 *
 * Class SlowQueryLogMiddleware
 * @package App\Http\Middleware
 */
class SlowQueryLogMiddleware
{
    public const SLOW_TIME = 1000;

    protected $exec;

    public function handle($request, Closure $next, $guard = null)
    {
        DB::enableQueryLog(); // 开启日记记录功能

        return $next($request);
    }

    public function terminate($request, $response)
    {
        if (!$response->isOk() || !$request->isMethod('get')) {
            return;
        }

        $this->exec = class_basename(optional($request->route())->getActionName());
        $result = $this->getSlowSqlInfo();

        // 写入操作
        if (!empty($result)) {
            SlowQueryLog::insert($result);
        }
    }

    public function getSlowSqlInfo()
    {
        $result = [];
        $data = DB::getQueryLog();

        if (!empty($data) && is_array($data)) {
            foreach ($data as $item) {
                if ($item['time'] >= static::SLOW_TIME) {
                    $result[] = [
                        'expend_time' => $item['time'],
                        'sql_content' => str_replace_array('?', $item['bindings'], $item['query']),
                        'ori_sql'     => $item['query'],
                        'exec'        => $this->exec,
                    ];
                }
            }
        }

        return $result;
    }
}